package com.lysj.bhp.system.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lysj.bhp.system.base.BaseConst;
import com.lysj.bhp.system.domain.Verify;
import com.lysj.bhp.system.repository.VerifyRepository;
import com.lysj.bhp.system.service.IpRecordService;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.user.repository.UserRepository;
import com.lysj.bhp.util.http.HttpUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("admin/pub")
public class PublicController extends BaseConst {
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    VerifyRepository verifyRepository;
    @Autowired
    IpRecordService ipRecordService;

    private static final long expires = 1000 * 60 * 3;

    @GetMapping(value = "/process")
    public Resp process() {
        return new Resp(Resp.SUCCESS, "success", BaseConst.ICO_PROCESS);
    }

    @PostMapping("/bcex")
    public Resp bcex() throws Exception {
        String btc2cny = HttpUtil.sendGet("https://www.bcex.top/coins/getBtcCny", "type=bcex");
        String markets = HttpUtil.sendGet("https://www.bcex.top/coins/markets", "t=" + Math.random());
        Map<String, String> respMap = new HashMap<>();
        respMap.put("btc2cny", btc2cny);
        respMap.put("markets", markets);
        return new Resp(Resp.SUCCESS, "success", respMap);
    }

    @RequestMapping("/verify")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String email) throws Exception {
        if (ParamUtil.isBlack(email)) {
            return;
        }
        if (!ipRecordService.verifyIp(request.getRemoteAddr())) { // 被拦截
            return;
        }


        Verify verify = new Verify();
        verify.setEmail(email);
        verify.setExpires(System.currentTimeMillis() + expires);

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            verify.setVerify(createText);
            System.out.println(createText);
//            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        verifyRepository.save(verify);

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");

        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

//    @Resource
//    DividendRepository dividendRepository;
//    @Resource
//    UserRepository userRepository;
//
//    @GetMapping(value = "/process1")
//    public Resp process1() {
//        List<Dividend> dividends = dividendRepository.findAll();
//        for (Dividend dividend : dividends) {
//            System.out.println("正在执行:" + dividend.getDividentId());
//            if (dividend.getDividentId() < 643) {
//                continue;
//            }
//            User user = userRepository.findOne(dividend.getUserId());
//            if (user == null) {
//                continue;
//            }
//            System.out.println("执行并添加到:" + dividend.getDividend() + ":" + dividend.getUserId());
//            user.setDividend(user.getDividend() + dividend.getDividend());
//            userRepository.save(user);
//        }
//
//        return new Resp(Resp.SUCCESS, "success", BaseConst.ICO_PROCESS);
//    }


}
